package org.jsola.hr.service.impl;

import org.jsola.common.StrKit;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IAttendExtraJsonDAO;
import org.jsola.hr.dto.AttendExtraJsonAddDTO;
import org.jsola.hr.dto.AttendExtraJsonUpdateDTO;
import org.jsola.hr.entity.AttendExtraJsonDO;
import org.jsola.hr.query.AttendExtraJsonQuery;
import org.jsola.hr.service.IAttendExtraJsonService;
import org.jsola.hr.vo.AttendExtraJsonListVO;
import org.jsola.hr.vo.AttendExtraJsonVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrAttendExtraJsonServiceImpl")
public class AttendExtraJsonServiceImpl implements IAttendExtraJsonService {

    @Autowired
    private IAttendExtraJsonDAO attendExtraJsonDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public AttendExtraJsonVO save(AttendExtraJsonAddDTO attendExtraJsonAddDTO, TokenUser tokenUser) {
        // 转DO
        AttendExtraJsonDO attendExtraJsonDO = attendExtraJsonAddDTO.to(AttendExtraJsonDO.class);
        // 保存
        attendExtraJsonDO = save(attendExtraJsonDO, tokenUser.getSiteId(), tokenUser.getUserId());
        //HrLogKit.logForSave("新增考勤方案额外数据", "saveAttendExtraJson", attendExtraJsonDO.getId(), tokenUser);
        return attendExtraJsonDO.to(AttendExtraJsonVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(AttendExtraJsonUpdateDTO attendExtraJsonUpdateDTO, TokenUser tokenUser) {
        //转DO
        AttendExtraJsonDO attendExtraJsonDO = attendExtraJsonUpdateDTO.to(AttendExtraJsonDO.class);
        //HrLogKit.logForUpdate("修改考勤方案额外数据", "updateAttendExtraJson", attendExtraJsonDO.getId(), tokenUser);
        //根据主键更新，只更新非null值
        return updateByIdSelective(attendExtraJsonDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... attendExtraJsonIds) {
//        HrLogKit.logForDelete("批量删除考勤方案额外数据", "deleteAttendExtraJsonByIds"
//                , Arrays.toString(attendExtraJsonIds), tokenUser);
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) attendExtraJsonIds);
    }


    @Override
    public AttendExtraJsonVO selectById(String attendExtraJsonId, String siteId) {
        AttendExtraJsonDO attendExtraJsonDO = selectDOById(attendExtraJsonId, siteId);
        if (attendExtraJsonDO == null) {
            return null;
        }
        return attendExtraJsonDO.to(AttendExtraJsonVO.class);
    }

    @Override
    public List<AttendExtraJsonListVO> select(AttendExtraJsonQuery attendExtraJsonQuery, String siteId) {
        List<AttendExtraJsonDO> attendExtraJsonDOList = selectDO(attendExtraJsonQuery, siteId);
        if (CollectionUtils.isEmpty(attendExtraJsonDOList)) {
            return attendExtraJsonDOList == null ? null : new ArrayList<>();
        }
        return attendExtraJsonDOList.stream()
                .map(attendExtraJsonDO -> attendExtraJsonDO.to(AttendExtraJsonListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(AttendExtraJsonQuery attendExtraJsonQuery, String siteId) {
        Example example = buildExample(attendExtraJsonQuery, siteId);
        return attendExtraJsonDAO.selectCountByExample(example);
    }

    @Override
    public Page<AttendExtraJsonListVO> selectPage(AttendExtraJsonQuery attendExtraJsonQuery, String siteId) {
        Example example = buildExample(attendExtraJsonQuery, siteId);
        Page<AttendExtraJsonDO> page = attendExtraJsonDAO.selectPageByExample(example,
                attendExtraJsonQuery.getPageNo(),
                attendExtraJsonQuery.getPageSize());

        return page.to(AttendExtraJsonListVO.class);
    }

    @Override
    public AttendExtraJsonDO selectDOById(String attendExtraJsonId, String siteId) {
        return listById(attendExtraJsonId, siteId);
    }

    @Override
    public List<AttendExtraJsonDO> selectDO(AttendExtraJsonQuery attendExtraJsonQuery, String siteId) {
        Example example = buildExample(attendExtraJsonQuery, siteId);
        return attendExtraJsonDAO.selectByExample(example);
    }

    @Override
    public int deleteByAttendPlanId(String attendPlanId, TokenUser tokenUser) {
        AttendExtraJsonQuery attendExtraJsonQuery = new AttendExtraJsonQuery();
        attendExtraJsonQuery.setAttendPalnId(attendPlanId);
        Example example = buildExample(attendExtraJsonQuery, tokenUser.getSiteId());
//        HrLogKit.logForDelete("考勤方案ID删除考勤方案额外数据（真实删除）"
//                , "deleteByAttendPlanId", attendPlanId, tokenUser);
        return attendExtraJsonDAO.deleteByExample(example);
    }

    @Override
    public int logicDelByAttendPlanId(String attendPlanId, TokenUser tokenUser) {

        // 查询
        AttendExtraJsonQuery attendExtraJsonQuery = new AttendExtraJsonQuery();
        attendExtraJsonQuery.setAttendPalnId(attendPlanId);
        List<AttendExtraJsonDO> dataList = this.selectDO(attendExtraJsonQuery, tokenUser.getSiteId());
        if (dataList.size() <= 0) {
            return 0;
        }

        for (AttendExtraJsonDO attendExtraJson : dataList) {

            AttendExtraJsonDO attendExtraJsonDO = new AttendExtraJsonDO();
            attendExtraJsonDO.setId(attendExtraJson.getId());
            attendExtraJsonDO.setValid(false);
            attendExtraJsonDO.setModifiedUserId(tokenUser.getUserId());
            attendExtraJsonDO.setGmtModified(new Date());
            attendExtraJsonDAO.updateByPrimaryKeySelective(attendExtraJsonDO);
        }

        return 0;
    }

    @Override
    public AttendExtraJsonDO selectByAttendPlanIdAndExtraType(String attendPlanId, Integer extraType, TokenUser tokenUser) {
        if (StrKit.isEmpty(attendPlanId) || Objects.isNull(extraType)) {
            throw new ParamException("考勤规则id及类型都不能为空");
        }
        Example example = new Example(AttendExtraJsonDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("attendPalnId", attendPlanId)
                .andEqualTo("extraType", extraType);
        example.setOrderByClause("gmt_create desc");
        List<AttendExtraJsonDO> attendExtraJsonDOList = attendExtraJsonDAO.selectByExample(example);
        if (CollectionUtils.isEmpty(attendExtraJsonDOList)) {
            return null;
        }
        return attendExtraJsonDOList.get(0);
    }


    /**
     * 根据查询参数，构建example
     *
     * @param attendExtraJsonQuery 查询参数
     * @param siteId               所属站点id
     * @return example
     */
    private Example buildExample(AttendExtraJsonQuery attendExtraJsonQuery, String siteId) {
        Example example = new Example(AttendExtraJsonDO.class);
        example.and()
                .andEqualTo("valid", true);
        if (siteId != null) {
            example.and().andEqualTo("siteId", siteId);
        }
        if (attendExtraJsonQuery.getAttendPalnId() != null) {
            example.and().andLike("attendPalnId", "%" + attendExtraJsonQuery.getAttendPalnId() + "%");
        }
        if (attendExtraJsonQuery.getExtraType() != null) {
            example.and().andEqualTo("extraType", attendExtraJsonQuery.getExtraType());
        }
        if (attendExtraJsonQuery.getJsonData() != null) {
            example.and().andLike("jsonData", "%" + attendExtraJsonQuery.getJsonData() + "%");
        }
        if (attendExtraJsonQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", attendExtraJsonQuery.getCompanyId());
        }
        if (attendExtraJsonQuery.getGmtCreateStart() != null &&
                attendExtraJsonQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", attendExtraJsonQuery.getGmtCreateStart(),
                    attendExtraJsonQuery.getGmtCreateEnd());
        }
        if (attendExtraJsonQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + attendExtraJsonQuery.getCreateUserId() + "%");
        }
        if (attendExtraJsonQuery.getGmtModifiedStart() != null &&
                attendExtraJsonQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", attendExtraJsonQuery.getGmtModifiedStart(),
                    attendExtraJsonQuery.getGmtModifiedEnd());
        }
        if (attendExtraJsonQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + attendExtraJsonQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example, attendExtraJsonQuery.getOrders());
        return example;
    }
}




